import {storageSession} from "@pureadmin/utils";
import Cookies from "js-cookie";


export const keyUserInfo = "user-info";

export type UserInfo = {
	code: number;
	msg: string;
	data: RootObjectData;
}
export type RootObjectDataInfoLoginInfo = {
	ipAddress: string;
	location: string;
	browser: string;
	operationSystem: string;
	loginTime: number;
}
export type RootObjectDataInfo = {
	userId: number;
	cachedKey: string;
	username: string;
	loginInfo: RootObjectDataInfoLoginInfo;
	autoRefreshCacheTime: number;
	vip: boolean;
	enabled: boolean;
}
export type RootObjectData = {
	token: string;
	info: RootObjectDataInfo;
}


/**
 *
 */
export class UserPreferenceStore {

    private static instance: UserPreferenceStore | null = null;

    private constructor() {
        // 私有构造函数，防止直接实例化
    }

    /**
     * 单例模式获取实例
     */
    static getInstance(): UserPreferenceStore {
        if (!UserPreferenceStore.instance) {
            UserPreferenceStore.instance = new UserPreferenceStore();
        }
        return UserPreferenceStore.instance;
    }

    /**
     * 清除用户信息
     */
    clearUserInfo(): void {
        Cookies.remove(keyUserInfo);
        storageSession().removeItem(keyUserInfo);
    }


    /**
     * 设置用户信息
     * @param data 用户信息
     */
    setUserInfo(data: UserInfo): void {

        const userInfo = JSON.stringify(data);
        // 存储到cookie中
        Cookies.set(keyUserInfo, userInfo);
        // 存储到sessionStorage中
        storageSession().setItem(keyUserInfo, userInfo);
    }

    /**
     * 获取手机号
     */
    getPhone(): string {
        let data = Cookies.get(keyUserInfo);
        if (data) {
            return JSON.parse(data).data.info.username;
        } else {
            return storageSession().getItem<UserInfo>(keyUserInfo)?.data.info.username
        }
    }

    /**
     * 获取token
     */
    getToken(): string {
        let data = Cookies.get(keyUserInfo);
        if (data && typeof data != 'undefined') {
            try {
                return JSON.parse(data).data?.token;
            } catch (e) {
                return "";
            }
        } else {
            return storageSession().getItem<UserInfo>(keyUserInfo)?.data?.token
        }
    }

}
